package com.junjie.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.junjie.springcloud.entities.CommonResult;
import com.junjie.springcloud.entities.Payment;
import com.junjie.springcloud.myhandler.CustomerBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author Yi Jun jie
 * @Date 2021/2/25 11:00
 */
@RestController
public class RateLimitController {
    @GetMapping("/byResource")
    //处理降级的方法名
    @SentinelResource(value = "byResource", blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult(200, "按照资源名限流测试0K", new Payment(2020L,"serial001"));
    }

    //降级方法
    public CommonResult handleException(BlockException e) {
        return new CommonResult(444, e.getClass().getCanonicalName() + "\t 服务不可用");
    }

    //这里的资源名称既可以用 /rateLimit/byUrl
    //来配也可以用 byUrl 来配置 (二者的效果一样只要保证唯一，注意：想要调用自定义兜底方法只能用 @SentinelResource 中的资源名字 )
    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl")
    public CommonResult byUrl() {
        return new CommonResult(200, "按 url 限流测试 OK", new Payment(2020L, "serial002"));
    }

    //自定义的限流处理兜底类
    @GetMapping("/rateLimit/CustomerBlockHandler")
    @SentinelResource(value = "CustomerBlockHandler",
                        blockHandlerClass = CustomerBlockHandler.class,
                           blockHandler = "handlerException1")
    public CommonResult CustomerBlockHandler() {
        return new CommonResult(200, "按客户自定义", new Payment(2020L, "serial003"));
    }
}
